import AliyunOSSUpload from '@/components/AliyunOSSUpload';
import { add_edit_broadcast, broadcast_plan_info } from '@/services/broadcast';
import { platform_select } from '@/services/instiution';
import { get_platformuser_select } from '@/services/patient';
import {
  ActionType,
  ProForm,
  ProFormGroup,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';
import {
  Button,
  DatePicker,
  Divider,
  Form,
  message,
  Modal,
  Table,
  TimePicker,
  Transfer,
} from 'antd';
import type { TableRowSelection } from 'antd/es/table/interface';
import type { TransferItem } from 'antd/es/transfer';
import dayjs from 'dayjs';
import difference from 'lodash/difference';
import moment from 'moment';
import { useEffect, useState } from 'react';
interface Iprops {
  isShowEditModal1: (show: boolean) => void;
  isEditModalOpen1: boolean;
  actionRef1: React.MutableRefObject<ActionType | undefined>;
  educationId: number | undefined;
}

// 穿梭框
const TableTransfer = ({ leftColumns, rightColumns, ...restProps }: any) => (
  <Transfer {...restProps}>
    {({
      direction,
      filteredItems,
      onItemSelectAll,
      onItemSelect,
      selectedKeys: listSelectedKeys,
      disabled: listDisabled,
    }) => {
      const columns = direction === 'left' ? leftColumns : rightColumns;

      const rowSelection: TableRowSelection<TransferItem> = {
        getCheckboxProps: (item) => ({ disabled: listDisabled || item.disabled }),
        onSelectAll(selected, selectedRows) {
          const treeSelectedKeys = selectedRows
            .filter((item) => !item.disabled)
            .map(({ key }) => key);
          const diffKeys = selected
            ? difference(treeSelectedKeys, listSelectedKeys)
            : difference(listSelectedKeys, treeSelectedKeys);
          onItemSelectAll(diffKeys as string[], selected);
        },
        onSelect({ key }, selected) {
          onItemSelect(key as string, selected);
        },
        selectedRowKeys: listSelectedKeys,
      };

      return (
        <Table
          rowSelection={rowSelection}
          scroll={{ y: 300 }}
          columns={columns}
          dataSource={filteredItems}
          pagination={false}
          size="small"
          rowKey={(record) => record.id}
          style={{ pointerEvents: listDisabled ? 'none' : undefined }}
        // onRow={({ key, disabled: itemDisabled }) => ({
        //   onClick: () => {
        //     if (itemDisabled || listDisabled) return;
        //     onItemSelect(key as string, !listSelectedKeys.includes(key as string));
        //   },
        // })}
        />
      );
    }}
  </Transfer>
);
const EditEducationTraining = (props: Iprops) => {
  const { isShowEditModal1, isEditModalOpen1, actionRef1, educationId } = props;
  const [form] = Form.useForm();
  // 直播背景图像地址
  const [imageUrl, setImageUrl] = useState(undefined);
  // 穿梭框
  const [targetKeys, setTargetKeys] = useState<string[]>();
  // 存储关联机构列表
  const [platformList, setPlatformList] = useState();
  // 存储主讲医生
  const [doctorlist, setDoctorlist] = useState([]);
  // 控制计划开始时间与计划结束时间的可选择范围
  const [dateDisabled, setDateDisabled] = useState(false);
  const [dateDisabled2, setDateDisabled2] = useState(false);
  // 存储直播计划详情信息
  const [broadcastPlanInfo, setBroadcastPlanInfo] = useState<any>(undefined);

  // 穿梭框相关方法
  const onChange = (nextTargetKeys: string[]) => {
    console.log('nextTargetKeys', nextTargetKeys);
    setTargetKeys(nextTargetKeys);
  };
  //穿梭框两侧表格列
  const leftTableColumns = [
    {
      dataIndex: 'name',
      title: '名称',
    },
    {
      dataIndex: 'province_name',
      title: '地区',
    },
  ];
  const rightTableColumns = [
    {
      dataIndex: 'name',
      title: '名称',
    },
    {
      dataIndex: 'province_name',
      title: '地区',
    },
  ];

  // 页面初始化，获取直播计划详情 获取机构列表数据和医生列表
  useEffect(() => {
    //   获取直播计划详情
    const getData = async () => {
      if (educationId) {
        let request_body = {
          id: educationId,
        };
        let res = await broadcast_plan_info(request_body);
        console.log('直播计划详情', res);
        setBroadcastPlanInfo(res.data);
        setImageUrl(res.data.icon);
        setTargetKeys(res.data.invite_platform);
      }
    };
    const get_platform_select = async () => {
      let res: any = await platform_select({ type: 2 });
      console.log('已绑定列表', res);
      if (res.msg == 'ok') {
        setPlatformList(res.data);
      }
    };
    const get_doctor = async () => {
      let res: any = await get_platformuser_select();
      console.log('res', res);
      res.data.map((item: any) => {
        item.value = item.id;
        item.label = item.username;
      });
      setDoctorlist(res.data);
    };
    getData();
    get_doctor();
    get_platform_select();
  }, []);

  const edit_broadcast = async (value: any) => {
    value.start_date = moment(value.start_date).format('YYYY-MM-DD ');
    value.start_time = moment(value.start_time).format('HH:mm:ss');
    value.end_time = moment(value.end_time).format('HH:mm:ss');
    // console.log(value);
    let request_body = {
      id: educationId,
      type: 2,
      name: value.name,
      platform_user_id: value.platform_user_id,
      start_time: value.start_date + value.start_time,
      end_time: value.start_date + value.end_time,
      range: 3,
      platform_list: JSON.stringify(targetKeys),
      // 可选
      icon: imageUrl,
      describe: value.describe ? value.describe : '',
    };
    if (JSON.parse(request_body.platform_list).length == 0) {
      message.error('请选择机构');
    } else {
      let res: any = await add_edit_broadcast(request_body);
      console.log('编辑成功', res);
      if (res.msg == 'ok') {
        actionRef1.current?.reload();
        message.success('编辑直播计划成功');
        isShowEditModal1(false);
      } else {
        message.error(res.msg);
      }
    }
  };
  // 直播日期禁用 (只能选择当天或者当天之后的时间)
  const disabledDate = (current: any) => {
    return current && current < moment().subtract(1, 'day');
  };

  // 直播日期发生变化时的回调
  const onChangedate = (date: any) => {
    // 当直播日期发生变化时，重置计划开始时间与计划结束时间
    form.setFieldsValue({ start_time: null, end_time: null });
    console.log('data', moment(date), new Date());
    const date1 = moment(date);
    const date2 = moment(new Date());
    if (date1.isSame(date2, 'day')) {
      setDateDisabled2(true);
    } else {
      setDateDisabled2(false);
    }
  };
  const range = (start: number, end: number) => {
    const result = [];
    for (let i = start; i < end; i++) {
      result.push(i);
    }
    return result;
  };
  // 禁用小时
  const disabledDateTime = () => {
    let nowHour = new Date().getHours();
    return {
      disabledHours: () => range(0, nowHour),
      disabledMinutes: () => [-1, 60],
      disabledSeconds: () => [0, 60],
    };
  };
  // 选择日期大于当前日期，不禁用小时
  const disabledDateTimeA = () => {
    return {
      disabledHours: () => [-1, 24],
      disabledMinutes: () => [-1, 60],
      // disabledSeconds: () => [-1, 60],
    };
  };
  // 切换禁用时分秒函数
  const handleDateChange = (date: any) => {
    console.log('date', date);
    const currentDate = moment(new Date()).valueOf();
    const clickDate = moment(date).valueOf();
    if (clickDate > currentDate) {
      setDateDisabled(true);
    } else {
      setDateDisabled(false);
    }
  };
  // 计划结束时间必须大于计划开始时间
  const validateEndTime = (rule: any, value: any, callback: any) => {
    const { getFieldValue } = form;
    const startTime = getFieldValue('start_time');
    if (value && startTime && value.isBefore(startTime)) {
      callback('计划结束时间必须大于计划开始时间');
    } else {
      callback();
    }
  };
  // 直播封面的删除
  const del = () => {
    setImageUrl(undefined);
  };
  return (
    <Modal
      title="编辑专业教培"
      open={isEditModalOpen1}
      onCancel={() => isShowEditModal1(false)}
      footer={null}
      destroyOnClose={true}
      centered
      width={1000}
    >
      <Divider />
      {broadcastPlanInfo === undefined ? (
        ''
      ) : (
        <ProForm
          form={form}
          onReset={() => isShowEditModal1(false)}
          onFinish={(value) => edit_broadcast(value)}
          submitter={{
            searchConfig: {
              submitText: '发布',
              resetText: '返回',
            },
            resetButtonProps: {
              style: {
                // 隐藏重置按钮
                display: 'block',
                position: 'absolute',
                left: 'calc(50% - 107px)',
              },
            },
            submitButtonProps: {
              style: {
                display: 'block',
                position: 'absolute',
                right: 'calc(50% - 107px)',
              },
            },
          }}
        >
          <ProFormGroup>
            <ProFormText
              width={280}
              name="name"
              label="直播主题"
              placeholder="请输入直播主题"
              rules={[
                {
                  required: true,
                  message: '请输入直播主题',
                  validateTrigger: 'onBlur',
                },
                { pattern: /(^\S)((.)*\S)?(\S*$)/, message: '不能输入空格' },
              ]}
              initialValue={broadcastPlanInfo.name}
            />
            <ProFormSelect
              width={320}
              name="platform_user_id"
              label="主讲医生"
              options={doctorlist}
              placeholder="请选择主讲医生"
              rules={[
                {
                  required: true,
                  message: '请选择主讲医生',
                },
              ]}
              initialValue={broadcastPlanInfo.platform_user_id}
            />
            <Form.Item
              name="start_date"
              label="直播日期"
              rules={[
                {
                  required: true,
                  message: '请选择直播日期',
                },
              ]}
              initialValue={moment(broadcastPlanInfo.start_time, 'YYYY/MM/DD')}
            >
              <DatePicker
                disabledDate={disabledDate}
                style={{ width: '280px' }}
                onChange={onChangedate}
              />
            </Form.Item>
          </ProFormGroup>
          <ProFormGroup>
            <Form.Item
              name="start_time"
              label="计划开始时间"
              rules={[
                {
                  required: true,
                  message: '请选择计划开始时间',
                },
              ]}
              initialValue={dayjs(
                moment(broadcastPlanInfo.start_time).format('HH:mm:00'),
                'HH:mm:00',
              )}
            >
              <TimePicker
                style={{ width: '280px' }}
                onChange={handleDateChange}
                format="HH:mm"
                disabledTime={dateDisabled2 ? disabledDateTime : disabledDateTimeA}
              />
            </Form.Item>
            <Form.Item
              name="end_time"
              label="计划结束时间"
              rules={[
                {
                  required: true,
                  message: '请选择计划结束时间',
                },
                {
                  validator: validateEndTime,
                },
              ]}
              initialValue={dayjs(
                moment(broadcastPlanInfo.end_time).format('HH:mm:00'),
                'HH:mm:00',
              )}
            >
              <TimePicker style={{ width: '320px' }} format="HH:mm" />
            </Form.Item>
          </ProFormGroup>
          <ProFormGroup>
            <Form.Item name="trans" label="授课范围">
              <TableTransfer
                titles={['管理中心列表', '已选管理中心']}
                dataSource={platformList}
                rowKey={(record: any) => record.id}
                targetKeys={targetKeys}
                showSearch={true}
                onChange={onChange}
                filterOption={(inputValue: any, item: { name: string; province_name: string }) =>
                  item.name!.indexOf(inputValue) !== -1 ||
                  item.province_name.indexOf(inputValue) !== -1
                }
                listStyle={{
                  height: 450,
                }}
                leftColumns={leftTableColumns}
                rightColumns={rightTableColumns}
              />
            </Form.Item>
          </ProFormGroup>
          <Form.Item name="icon" label="直播封面" extra="建议上传690*360的图片作为封面">
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <AliyunOSSUpload imageUrl={imageUrl} setImageUrl={setImageUrl}></AliyunOSSUpload>
              <Button style={{ marginLeft: '20px' }} onClick={del}>
                删除
              </Button>
            </div>
          </Form.Item>
          <ProFormGroup>
            <ProFormTextArea
              initialValue={broadcastPlanInfo.describe}
              width={900}
              label="介绍"
              name="describe"
              placeholder="请输入直播介绍"
              rules={[
                { max: 100, message: '字数限制为100字符' },
                { required: true, message: '请填写直播介绍' },
                { pattern: /(^\S)((.)*\S)?(\S*$)/, message: '不能输入空格' },
              ]}
            />
          </ProFormGroup>
          <br />
        </ProForm>
      )}
    </Modal>
  );
};
export default EditEducationTraining;
